//
//  JJToastView.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/25.
//

import UIKit

/// 用于在屏幕中间显示的toast蒙版
public class JJCenterToastView: UIView {
    private let animationTime: Double = 0.4
    
    private var centerView: UIView?
    
    /// 创建用于在屏幕中间显示的toast蒙版
    /// - Parameters:
    ///   - centerView: 中间显示内容的view
    ///   - widthFactor: view宽度系数[0.1, 1]表示widthFactor*deviceWidth，如果值为[100, deviceWidth]表示所有机型都一样的宽度，如果不设置widthFactor则用自身的宽
    ///   - tapHide: 点击蒙版是否隐藏
    /// - Returns: 返回对象
    static func creat(centerView: UIView, widthFactor: CGFloat = CGFloat.zero, tapHide: Bool) -> JJCenterToastView? {
        let toast = JJCenterToastView(frame: UIDevice.screenBounds)
        toast.backgroundColor = .hex("#000000", 0.4)
        if tapHide {
            let btn = UIButton(type: .custom)
            btn.frame = toast.bounds
            btn.setTitle("", for: .normal)
            btn.addTarget(toast, action: #selector(hide), for: .touchUpInside)
            toast.addSubview(btn)
        }
        toast.addSubview(centerView)
        guard let inView = UIApplication.shared.delegate?.window, inView != nil else {
            return nil
        }
        let width: CGFloat
        let height: CGFloat = min((UIDevice.height - 100), centerView.height)
        switch widthFactor {
        case CGFloat.zero:
            width = centerView.width
        case 0.1...1:
            width = widthFactor * inView!.width
        case 100...inView!.width:
            width = widthFactor
        default:
            width = 0.8 * inView!.width
        }
        centerView.frame = CGRect(x: (inView!.width - width) * 0.5, y: (inView!.height - height) * 0.5, width: width, height: height)
        /**
         用代码创建的所有view ， translatesAutoresizingMaskIntoConstraints 默认是 YES
         用 IB 创建的所有 view ，translatesAutoresizingMaskIntoConstraints 默认是 NO (autoresize 布局:YES , autolayout布局 :NO)
         如果是xib创建的需要修改Layout设置为Auto
         */
        if !centerView.translatesAutoresizingMaskIntoConstraints || (widthFactor >= 0.1 && widthFactor <= 1) {
            centerView.snp.makeConstraints({ make in
                make.center.equalToSuperview()
                make.width.equalTo(width)
                make.height.equalTo(height)
            })
        }
        toast.centerView = centerView
        inView?.addSubview(toast)
        return toast
    }
    
    @objc static func hide() {
        guard let inView = UIApplication.shared.delegate?.window else {
            return
        }
        inView?.subviews.forEach({ subView in
            if type(of: subView) == self {
                (subView as! JJCenterToastView).hiddenAnimation()
            }
        })
    }
    
    /// 动画显示
    func showAnimation() {
        guard let center = centerView else {
            return
        }
        center.alpha = 0
        UIView.animate(withDuration: animationTime) {
            center.alpha = 1.0
        }
    }
    
    /// 动画隐藏
    func hiddenAnimation() {
        guard let center = centerView else {
            return
        }
        UIView.animate(withDuration: animationTime) {
            center.alpha = 0
        } completion: { finished in
            self.removeFromSuperview()
        }
    }
}

/// 下拉展示蒙版
public class JJDownShowView: UIView {
    var mengban: UIView?
    public override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        backgroundColor = .clear
        let mengban = UIView(frame: frame)
        mengban.backgroundColor = .hex("#000000", 0.4)
        mengban.clipsToBounds = true
        addSubview(mengban)
        self.mengban = mengban
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// 从底部向上动画展示的蒙版
public class JJUpShowView: UIView {
    public override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        backgroundColor = .hex("#000000", 0.4)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

/// 从右边向左动画展示的蒙版
public class JJLeftShowView: UIView {
    public override init(frame: CGRect) {
        super.init(frame: UIScreen.main.bounds)
        backgroundColor = .hex("#000000", 0.4)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

public extension UIView {
    
    /// 在屏幕中间动画展示
    /// - Parameters:
    ///   - widthFactor: view宽度系数[0.1, 1]表示widthFactor*deviceWidth，如果值为[100, deviceWidth]表示所有机型都一样的宽度，如果不设置widthFactor则用自身的宽
    ///   - tapHide: 点击蒙版是否隐藏
    func showCenter(widthFactor: CGFloat = CGFloat.zero, tapHide: Bool = true) {
        let toast = JJCenterToastView.creat(centerView: self, widthFactor: widthFactor, tapHide: tapHide)
        toast?.showAnimation()
    }
    
    /// 隐藏屏幕中间的弹窗内容
    func hiddenCenter() {
        JJCenterToastView.hide()
    }
    
    /// 下拉展示
    /// - Parameters:
    ///   - relyView: 依赖的下拉展示控件，用来定位从哪里下拉
    ///   - tapHide: 点击其他区域是否隐藏
    func downOpen(relyView: UIView, tapHide: Bool = true) {
        guard let inView = UIApplication.shared.delegate?.window, let superrView = inView else {
            return
        }
        let relyFrame = relyView.convert(relyView.bounds, to: self.superview)
        let showFrame = CGRectMake(0, relyFrame.origin.y + relyFrame.size.height, superrView.width, superrView.height)
        let bgView = JJDownShowView(frame: showFrame)
        superrView.addSubview(bgView)
        let viewFrame = self.frame
        bgView.mengban?.addSubview(self)
        self.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(0)
        }
        bgView.layoutIfNeeded()
        if tapHide {
            let tapView = UIView()
            tapView.backgroundColor = .clear
            tapView.addTap { [weak self] sender in
                guard let `self` = self else { return }
                upClose()
            }
            bgView.mengban?.addSubview(tapView)
            tapView.snp.makeConstraints { make in
                make.top.equalTo(self.snp.bottom)
                make.left.right.bottom.equalToSuperview()
            }
        }
        self.snp.updateConstraints { make in
            make.height.equalTo(viewFrame.size.height)
        }
        UIView.animate(withDuration: 0.3) {
            bgView.layoutIfNeeded()
        }
    }
    
    /// 向上收起动画并移除
    func upClose() {
        guard let inView = UIApplication.shared.delegate?.window, let superrView = inView else {
            return
        }
        superrView.subviews.forEach { subView in
            if type(of: subView) == JJDownShowView.self {
                let tempView = subView as! JJDownShowView
                if tempView.subviews.contains(self) {
                    self.snp.updateConstraints { make in
                        make.height.equalTo(0)
                    }
                    UIView.animate(withDuration: 0.3) {
                        tempView.layoutIfNeeded()
                    } completion: { finished in
                        self.removeFromSuperview()
                        tempView.removeFromSuperview()
                    }
                }
            }
        }
    }
    
    /// 向上动画展示
    /// - Parameter tapHide: 点击其他区域是否隐藏
    func upOpen(tapHide: Bool = true) {
        guard let inView = UIApplication.shared.delegate?.window, let superrView = inView else {
            return
        }
        let bgView = JJUpShowView(frame: superrView.bounds)
        superrView.addSubview(bgView)
        bgView.addSubview(self)
        self.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(bgView.snp.bottom)
        }
        bgView.layoutIfNeeded()
        if tapHide {
            let tapView = UIView()
            tapView.backgroundColor = .clear
            tapView.addTap { [weak self] sender in
                guard let `self` = self else { return }
                downClose()
            }
            bgView.addSubview(tapView)
            tapView.snp.makeConstraints { make in
                make.left.right.top.equalToSuperview()
                make.bottom.equalTo(self.snp.top)
            }
        }
        self.snp.remakeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        UIView.animate(withDuration: 0.3) {
            bgView.layoutIfNeeded()
        }
    }
    
    /// 向下动画隐藏
    func downClose() {
        guard let inView = UIApplication.shared.delegate?.window, let superrView = inView else {
            return
        }
        superrView.subviews.forEach { subView in
            if type(of: subView) == JJUpShowView.self {
                let tempView = subView as! JJUpShowView
                if tempView.subviews.contains(self) {
                    self.snp.remakeConstraints { make in
                        make.left.right.equalTo(tempView)
                        make.top.equalTo(tempView.snp.bottom)
                    }
                    UIView.animate(withDuration: 0.3) {
                        tempView.layoutIfNeeded()
                    } completion: { finished in
                        self.removeFromSuperview()
                        tempView.removeFromSuperview()
                    }
                }
            }
        }
    }
    
    /// 向左动画展示
    /// - Parameter tapHide: 点击其他区域是否隐藏
    func leftOpen(tapHide: Bool = true, inView: UIView? = nil) {
        var superrView = inView == nil ? UIWindow() : UIView()
        if let tempInView = inView {
            superrView = tempInView
        } else {
            guard let windowView = UIApplication.shared.delegate?.window, let tempWindow = windowView else {
                return
            }
            superrView = tempWindow
        }
        let bgView = JJLeftShowView(frame: superrView.bounds)
        superrView.addSubview(bgView)
        bgView.addSubview(self)
        self.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(bgView.snp.right)
        }
        bgView.layoutIfNeeded()
        if tapHide {
            let tapView = UIView()
            tapView.backgroundColor = .clear
            tapView.addTap { [weak self] sender in
                guard let `self` = self else { return }
                rightClose(inView: inView)
            }
            bgView.addSubview(tapView)
            tapView.snp.makeConstraints { make in
                make.left.top.bottom.equalToSuperview()
                make.right.equalTo(self.snp.left)
            }
        }
        self.snp.remakeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.width.lessThanOrEqualTo(bgView.width * 0.8)
        }
        UIView.animate(withDuration: 0.3) {
            bgView.layoutIfNeeded()
        }
    }
    
    /// 向右动画隐藏
    func rightClose(inView: UIView? = nil) {
        var superrView = inView == nil ? UIWindow() : UIView()
        if let tempInView = inView {
            superrView = tempInView
        } else {
            guard let windowView = UIApplication.shared.delegate?.window, let tempWindow = windowView else {
                return
            }
            superrView = tempWindow
        }
        superrView.subviews.forEach { subView in
            if type(of: subView) == JJLeftShowView.self {
                let tempView = subView as! JJLeftShowView
                if tempView.subviews.contains(self) {
                    self.snp.remakeConstraints { make in
                        make.top.bottom.equalTo(tempView)
                        make.left.equalTo(tempView.snp.right)
                    }
                    UIView.animate(withDuration: 0.3) {
                        tempView.layoutIfNeeded()
                    } completion: { finished in
                        self.removeFromSuperview()
                        tempView.removeFromSuperview()
                    }
                }
            }
        }
    }
}
